package com.filetransfer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Controller
public class UserController {

    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    private static final ConcurrentHashMap<String, UserInfo> onlineUsers = new ConcurrentHashMap<>();

    @MessageMapping("/user.connect")
    public void handleUserConnect(UserStatus status, SimpMessageHeaderAccessor headerAccessor) {
        String ipAddress = headerAccessor.getSessionAttributes().get("ip").toString();
        onlineUsers.put(status.getDeviceId(), new UserInfo(status.getDeviceId(), ipAddress));
        broadcastUserList();
    }

    @MessageMapping("/user.disconnect")
    public void handleUserDisconnect(UserStatus status) {
        onlineUsers.remove(status.getDeviceId());
        broadcastUserList();
    }

    private void broadcastUserList() {
        List<UserInfo> userList = new ArrayList<>(onlineUsers.values());
        messagingTemplate.convertAndSend("/topic/users", new UsersUpdate(userList));
    }

    public static class UserInfo {
        private String deviceId;
        private String ipAddress;

        public UserInfo() {
        }

        public UserInfo(String deviceId, String ipAddress) {
            this.deviceId = deviceId;
            this.ipAddress = ipAddress;
        }

        public String getDeviceId() {
            return deviceId;
        }

        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }

        public String getIpAddress() {
            return ipAddress;
        }

        public void setIpAddress(String ipAddress) {
            this.ipAddress = ipAddress;
        }
    }

    public static class UserStatus {
        private String deviceId;
        private String status;

        public String getDeviceId() {
            return deviceId;
        }

        public void setDeviceId(String deviceId) {
            this.deviceId = deviceId;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }
    }

    public static class UsersUpdate {
        private List<UserInfo> users;

        public UsersUpdate(List<UserInfo> users) {
            this.users = users;
        }

        public List<UserInfo> getUsers() {
            return users;
        }
    }
}